package io.github.kimmking.kkconfig.spring;

import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

/**
 * Description for this class.
 *
 * @Author : kimmking(kimmking@apache.org)
 * @create 2024/4/19 00:48
 */

@Data
public class PropertySourcesProcessor implements BeanFactoryPostProcessor,
        ApplicationContextAware, EnvironmentAware, PriorityOrdered {

    public static final String KK_PROPERTY_SOURCES_NAME = "KKPropertySources";
    public static final String KK_PROPERTY_SOURCE_NAME = "KKPropertySource";

    Environment environment;
    ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        ConfigurableEnvironment ENV = (ConfigurableEnvironment)environment;
        if(ENV.getPropertySources().contains(KK_PROPERTY_SOURCE_NAME)) {
            return;
        }
        String app = environment.getProperty("app", "app1");
        String ns = environment.getProperty("ns", "public");
        String env = environment.getProperty("env", "dev");
        String configServer = environment.getProperty("configServer", "http://localhost:9129");
        ConfigMeta metadata = new ConfigMeta(app, ns, env, configServer);

        KKConfigService configService = KKConfigService.getDefault(applicationContext, metadata);
        CompositePropertySource composite = new CompositePropertySource(KK_PROPERTY_SOURCES_NAME);
        KKPropertySource KKPropertySource = new KKPropertySource(KK_PROPERTY_SOURCE_NAME, configService);
        composite.addPropertySource(KKPropertySource);
        ENV.getPropertySources().addFirst(composite);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
